#include "stdSqliteDataBase.h"
#include <string>


stdSqliteDataBase::stdSqliteDataBase()
{
   
    this->db=NULL;
}

stdSqliteDataBase::~stdSqliteDataBase()
{
    
}

bool stdSqliteDataBase::connect(const char * hostname)
{
    int ret = sqlite3_open(hostname, &db);
    if (ret != SQLITE_OK) 
    {
        std::cout << "Error: " << sqlite3_errmsg(db) << std::endl;
        return false;
    }
  
    return true;
}

QueryResult stdSqliteDataBase::query(const std::string &sql)
{

    QueryResult result;

    char **pazResult=NULL;
    int pnRow=0;
    int pnColumn=0;
    int ret=sqlite3_get_table(db,sql.c_str(),&(pazResult),&pnRow,&pnColumn,NULL);
    std::cout<<"pnRow:"<<pnRow<<"pnColumn:"<<pnColumn<<std::endl;
    if (ret != SQLITE_OK) 
    {
        std::cout << "Error: " << sqlite3_errmsg(db) << std::endl;
        return result;
    }

    for(int i=1;i<=pnRow;i++)
    {
        std::vector<std::string> rowdata;
        for(int j=0;j<pnColumn;j++)
        {
           std::cout<<i<<"   "<<j<<std::endl;
           rowdata.push_back(pazResult[i*pnColumn+j]);
           std::cout<<pazResult[i*pnColumn+j]<<std::endl;
        }
        result.datas.push_back(rowdata);
    }
    sqlite3_free_table(pazResult);
    return result;
}

// 执行 执行语句
bool stdSqliteDataBase::execute(const std::string &sql)
{
    int ret = sqlite3_exec(db, sql.c_str(), NULL, NULL, NULL);
    if (ret != SQLITE_OK)
    {
        std::cout << "Error: " << sqlite3_errmsg(db) << std::endl;
        return false;
    }
    return true;
}

void stdSqliteDataBase::close()
{
    sqlite3_close(db);
}
